import React, {useState} from 'react';
import {Button, InputItem, Toast} from '@ant-design/react-native';
import {View, Text, StyleSheet} from 'react-native';
import req from '../../http/http';
import useStorage from '../../hooks/storage';
import jwt from 'jwt-decode';
import {TUserInfo} from '../../type/TUser';
const Login = ({navigation}) => {
  const [username, setUsername] = useState<string>('');
  const [password, setPassowrd] = useState<string>('');
  const tokenStorage = useStorage('token');
  const userInfoStorage = useStorage('userInfo');
  const login = () => {
    if (username.trim() === '' || password.trim() === '') {
      Toast.success({
        content: '123',
        duration: 5,
      });
      return;
    }
    req
      .post('/user/login', {
        username,
        password,
      })
      .then(res => {
        console.log(res);
        if (res.error === -1) {
          const token = res.data;
          const userInfo = jwt<TUserInfo>(token);
          userInfoStorage.setItem(userInfo);
          tokenStorage.setItem(token);
          navigation.push('主页');
        }
      });
  };
  const goForget = () => {
    navigation.push('忘记密码');
  };
  const goRegister = () => {
    navigation.push('注册');
  };
  return (
    <>
      <View style={{padding: 15}}>
        <InputItem
          clear
          value={username}
          onChange={(value: string) => {
            setUsername(value);
          }}
          labelNumber={3}
          placeholder="请输入用户名">
          用户名
        </InputItem>
        <InputItem
          clear
          value={password}
          type="password"
          onChange={(value: string) => {
            setPassowrd(value);
          }}
          labelNumber={3}
          placeholder="请输入密码">
          密码
        </InputItem>
        <View>
          <Text onPress={() => goForget()} style={styles.forgetPassword}>
            忘记密码?
          </Text>
        </View>
        <View>
          <Button
            type="primary"
            onPress={() => login()}
            style={{marginBottom: 10}}>
            登录
          </Button>
          <Button onPress={() => goRegister()} type="ghost">
            注册
          </Button>
        </View>
      </View>
    </>
  );
};
const styles = StyleSheet.create({
  forgetPassword: {
    color: '#377df6',
    textAlign: 'right',
    margin: 10,
  },
});
export default Login;
